package com.findyou.headline.controller;

import com.findyou.headline.common.Result;
import com.findyou.headline.pojo.NewsType;
import com.findyou.headline.pojo.vo.HeadlineDetailVo;
import com.findyou.headline.pojo.vo.HeadlineQueryVo;
import com.findyou.headline.service.NewsHeadlineService;
import com.findyou.headline.service.NewsTypeService;
import com.findyou.headline.service.impl.NewsHeadlineServiceImpl;
import com.findyou.headline.service.impl.NewsTypeServiceImpl;
import com.findyou.headline.util.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
门户控制器
那些不需要登录 不需要做增删改查的门户页的请求都放在这里
 */
@WebServlet("/portal/*")
public class PortalController extends BaseController{
    private NewsTypeService typeService = new NewsTypeServiceImpl();
    private NewsHeadlineService headlineService = new NewsHeadlineServiceImpl();

    /**
     * 查询所有的新闻类型业务接口实现
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void findAllTypes(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<NewsType> newsTypeList = typeService.findAll();
        WebUtil.writeJson(resp, Result.ok(newsTypeList)); //     // 将Result对象转换成JSON串并放入响应对象
    }

    /**
     *分页查询头条信息的接口实现
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void findNewsPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收请求中的参数
        HeadlineQueryVo headlineQueryVo = WebUtil.readJson(req, HeadlineQueryVo.class);
        //将参数传递给服务层 进行分页查询
        /*
        pageInfo 可不轻松啊
        要求包含下面这些
        pageData: 数组 [
            {
                "hid"
                "title"
                ......
            }
        ]
        pageNum:1
        pageSize:1
        totalPage:1
        totalSize:1
         */
        Map pageInfo = headlineService.findPage(headlineQueryVo);
        Map data = new HashMap();
        data.put("pageInfo", pageInfo);

        // 将分页查询的结果转化成JSON响应给客户端
        WebUtil.writeJson(resp, Result.ok(data));
    }

    /**
     *查询头条详情的业务接口实现
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void showHeadlineDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收要查询新闻的id
        int hid = Integer.parseInt(req.getParameter("hid"));
        //调用服务层 完成查询处理
        HeadlineDetailVo headlineDetailVo = headlineService.findHeadlineDetail(hid);
        //将查询到的信息 响应给客户端
        Map data = new HashMap();
        data.put("headline", headlineDetailVo);
        WebUtil.writeJson(resp, Result.ok(data));
    }
}
